package cn.lg.soar.database.handler;

import cn.lg.soar.common.util.current.ICurrentUser;
import cn.lg.soar.common.util.current.UserContext;
import cn.lg.soar.database.base.entity.IBaseEntity;
import cn.lg.soar.database.base.entity.ITenantEntity;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

import java.time.LocalDateTime;

/**
 * 不开启多租户时生效
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@ConditionalOnProperty(name = ITenantEntity.CONFIG_NAME, havingValue = "false", matchIfMissing = true)
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        // 当前时间当前用户
        ICurrentUser user = UserContext.getUserOrDef();
        Long userId = user.getId();
        LocalDateTime now = LocalDateTime.now();
        // 原始类
        Object object = metaObject.getOriginalObject();
        if (object instanceof IBaseEntity) {
            IBaseEntity entity = (IBaseEntity) object;
            entity.setCreateTime(now);
            entity.setUpdateTime(now);
            entity.setCreateBy(userId);
            entity.setUpdateBy(userId);
        } else {
            this.setFieldValByName("createTime", now, metaObject);
            this.setFieldValByName("updateTime", now, metaObject);
            this.setFieldValByName("createBy", userId, metaObject);
            this.setFieldValByName("updateBy", userId, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        ICurrentUser user = UserContext.getUserOrDef();
        Long userId = user.getId();
        LocalDateTime now = LocalDateTime.now();
        // 原始类
        Object object = metaObject.getOriginalObject();
        if (object instanceof IBaseEntity) {
            IBaseEntity entity = (IBaseEntity) object;
            entity.setUpdateTime(now);
            entity.setUpdateBy(userId);
        } else {
            this.setFieldValByName("updateTime", now, metaObject);
            this.setFieldValByName("updateBy", userId, metaObject);
        }
    }

}
